// 云函数入口文件
const cloud = require("wx-server-sdk");
const qs = require("qs");
const GBK = require("gbk.js");

cloud.init();

let db = cloud.database();
let _ = db.command;

/**
 * 搜索记录
 * @param {string} value
 * @param {string} openid
 */
async function serachLog(value, openid) {
  // 搜索历史记录
  db.collection("search_histories")
    .where({
      name: value,
      _openid: openid
    })
    .count()
    .then(res => {
      if (res.total > 0) {
        db.collection("search_histories")
          .where({
            name: value,
            _openid: openid
          })
          .update({
            data: {
              updated_at: new Date().getTime()
            }
          });
      } else {
        db.collection("search_histories").add({
          data: {
            name: value,
            _openid: openid,
            updated_at: new Date().getTime()
          }
        });
        // 最多保留10条搜索记录
        db.collection("search_histories")
          .where({
            _openid: openid
          })
          .count()
          .then(res => {
            if (res.total > 9) {
              db.collection("search_histories")
                .where({
                  _openid: openid
                })
                .orderBy("updated_at", "asc")
                .limit(1)
                .get()
                .then(res => {
                  db.collection("search_histories")
                    .doc(res.data[0]._id)
                    .remove();
                });
            }
          });
      }
    })
    .catch(console.error);

  // 搜索记录统计
  db.collection("search_count")
    .where({
      name: value
    })
    .count()
    .then(res => {
      if (res.total > 0) {
        db.collection("search_count")
          .where({
            name: value
          })
          .update({
            data: {
              count: _.inc(1)
            }
          });
      } else {
        db.collection("search_count").add({
          data: {
            name: value,
            count: 1
          }
        });
      }
    });
}

/**
 * 获得请求地址
 * @param {string} url
 * @param {string} type
 * @param {object} searchData
 * @param {string} value
 */
function getUrl(url, searchData, value) {
  const { key, extraData, type } = searchData;
  if (key) extraData[key] = value;
  let searchUrl = url + qs.stringify(extraData, { encode: false });
  if (type == "gbk") {
    searchUrl = GBK.URI.encodeURI(searchUrl);
  } else {
    searchUrl = encodeURI(searchUrl);
  }
  return searchUrl;
}

/**
 * 拼接post数据
 */
function getPostData(postData, value) {
  if (!postData) {
    return {}
  }
  const { key, extraData, type } = postData
  const data = {}
  if (key) {
    data[key] = type == "gbk" ? GBK.URI.encodeURI(value) : value
  }
  if (extraData) {
    for (const i in extraData) {
      data[i] = type == "gbk" ? GBK.URI.encodeURI(extraData[i]) : extraData[i]
    }
  }
  return data
}

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();

  cloud.updateConfig({
    env: wxContext.ENV == "local" ? "test-go5gy" : wxContext.ENV
  });

  db = cloud.database();
  _ = db.command;

  const { pageIndex, value, source_id } = event;
  if (pageIndex == 1) {
    serachLog(value, wxContext.OPENID);
  }

  const source = await db
    .collection("book_sources")
    .doc(source_id)
    .field({ search: true, pageSize: true })
    .get();

  let data = [];
  if (source.errMsg == "document.get:ok" && source.data) {
    const {
      pageSize,
      search: { searchData, postData, result, url, type, method }
    } = source.data;
    const searchUrl = getUrl(url, searchData, value);
    const _postData = getPostData(postData, value)
    const res = await cloud.callFunction({
      name: "worm",
      data: {
        url: searchUrl,
        method,
        postData: _postData,
        result,
        type,
        slice: true,
        pageIndex,
        pageSize
      }
    });
    if (res.result && res.result.data) {
      data = res.result.data;
      data.forEach(item => {
        item.source_id = source.data._id;
      });
    } else {
      return {
        errMsg: "搜索失败"
      };
    }
  } else {
    return {
      errMsg: "没有小说源"
    };
  }

  return { errMsg: "ok", data };
};
